package com.liuyu.common.framework.common.util;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * Id 生成器
 *
 * @author: liuyu
 * @date: 2022/4/14 9:01
 * @version: 1
 */
public class IdUtils {
    private static SecureRandom RANDOM;

    private IdUtils() {
    }


    static {
        try {
            RANDOM = SecureRandom.getInstance("SHA1PRNG");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    private static final Snowflake SNOWFLAKE = IdUtil.getSnowflake(1, 1);

    /**
     * 雪花算法
     *
     * @return long
     * @author liuyu
     * @date 2022/4/14 9:04
     */
    public static long snowflakeNextId() {
        return SNOWFLAKE.nextId();
    }

    /**
     * 雪花算法
     */
    public static String snowflakeNextIdStr() {
        return SNOWFLAKE.nextIdStr();
    }

    /**
     * 生成短的UUID
     *
     * @return java.lang.String
     * @author liuyu
     * @date 2022/4/14 9:17
     */
    public static String simpleUuid() {
        return IdUtil.simpleUUID();
    }


    /**
     * 生成指定位数的随机数
     *
     * @param randomLength
     * @return java.lang.String
     * @throws
     * @author liuyu
     * @date 2022/12/1 12:54
     */
    public static String creatRandomNum(Integer randomLength) {
        Integer length = 1;
        for (Integer i = 0; i < randomLength; i++) {
            length *= 10;
        }
        int seed = (int) Math.ceil(RANDOM.nextFloat() * length);
        String captcha = String.valueOf(seed);
        while (captcha.length() < randomLength) {
            seed = (int) Math.ceil(RANDOM.nextFloat() * length);
            captcha = String.valueOf(seed);
        }
        return captcha;
    }
}
